package com.jk.kq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jk.common.base.BaseServiceImpl;
import com.jk.common.bean.ReturnBean;
import com.jk.common.bean.ReturnCode;
import com.jk.common.util.ImageUtils;
import com.jk.file.entity.FileResult;
import com.jk.file.mapper.FileResultMapper;
import com.jk.kq.common.GeneralConvertor;
import com.jk.kq.constant.SystemCons;
import com.jk.kq.entity.JkDeviceAds;
import com.jk.kq.entity.dto.JkDeviceAdsDTO;
import com.jk.kq.mapper.JkDeviceAdsMapper;
import com.jk.kq.service.IJkDeviceAdsService;
import com.jk.sys.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import java.io.File;
import java.io.IOException;


/**
 * 广告位服务接口实现层
 * @author 张威伦
 * @version 1.0
 * @date 2020年06月12日
 */
@Service
public class JkDeviceAdsServiceImpl extends BaseServiceImpl<JkDeviceAdsMapper, JkDeviceAds> implements IJkDeviceAdsService {


    @Autowired
    private FileResultMapper fileMapper;


    @Autowired
    private DeviceService deviceService;

    @Autowired
    private GeneralConvertor convertor;


    @Override
    @Transactional
    public ReturnBean insertAndCmd(JkDeviceAdsDTO dto) throws IOException {

        String imgUrl = dto.getImgUrl();
        if (ObjectUtils.isEmpty(imgUrl)){
            return ReturnBean.error(ReturnCode.INVALID_REQUEST.getCode(),"图片url为空");
        }
        QueryWrapper<FileResult> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("url",imgUrl);
        FileResult fileResult = fileMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(fileResult) || ObjectUtils.isEmpty(fileResult.getSavePath()) ) {
            return ReturnBean.error(ReturnCode.INVALID_REQUEST.getCode(),"文件表不存在或者保存地址为空，检查文件地址");
        }

        //
        return insertAndsend(fileResult,dto);
    }

    @Override
    public ReturnBean delAndSend(JkDeviceAds dto) {
        deviceService.delImg(SystemCons.Device.deviceId,dto.getImgIndex());
        return ReturnBean.ok();
    }

    @Transactional
    ReturnBean insertAndsend(FileResult fileResult, JkDeviceAdsDTO dto) throws IOException {
        String img = ImageUtils.encodeImgageToBase64(new File(fileResult.getSavePath()));
//
//        Thumbnails.of(fileResult.getSavePath())
//                .size(500, 500)
//                .toFile("C:\\Users\\Administrator\\Desktop\\newmeinv.png");

        deviceService.updateImg(SystemCons.Device.deviceId,dto.getImgIndex(),img);
        //类型转换
        JkDeviceAds entity = this.convertor.convertor(dto, JkDeviceAds.class);
        insert(entity);
        return ReturnBean.ok();
    }
}
